//
//  AppDelegate.swift
//  XYWeibo
//
//  Created by 常晓璇 on 6/23/15.
//  Copyright © 2015 chang xiaoxuan. All rights reserved.
//

import UIKit
import AFNetworking

///  全局变量记录用户账号
var sharedUserAccount = UserAccount.loadAccount()
 /// 切换跟控制器的通知
let XYSwitchRootVCNotification = "XYSwitchRootVCNotification"


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
       
        // 设置网络指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        // 设置网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4*1024*1024, diskCapacity: 20*1024*1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)
        
        // 打印归档保存的用户信息
        print(UserAccount.loadAccount())
        // 设置外观
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.redColor()
        
        window?.rootViewController = defaultViewController()
        window?.makeKeyAndVisible()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: XYSwitchRootVCNotification, object: nil)
        return true
    }
    
    ///  设置外观
    private func setupAppearance() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
    ///  切换控制器
    func switchViewController(n:NSNotification) {
        let isMainVC = n.object as! Bool
        window?.rootViewController = isMainVC ? MainViewController () : WelcomeViewController()
    }
    ///  判断加载的默认控制器
    private func defaultViewController() -> UIViewController {
        if sharedUserAccount != nil {
            return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
        }
        return MainViewController()
    }
    ///  判断是否新版本
    private func isNewUpdate() -> Bool {
        // 获取应用的当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = NSNumberFormatter().numberFromString(currentVersion)!.doubleValue
        
        // 获取应用程序'之前的版本', 从用户偏好中读取
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        
        // 将'当前版本'写入用户偏好
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
        
        return version > sandBoxVersion
    }
    
    


}

